package com.seashop.service.impl;

import com.seashop.constant.BaseConstant;
import com.seashop.entity.AppHomeConfig;
import com.seashop.feign.ManageFeignClient;
import com.seashop.feign.ProductFeignClient;
import com.seashop.feign.ThirdFeignClient;
import com.seashop.mapper.AppHomeConfigMapper;
import com.seashop.request.GoogleTransRequestParam;
import com.seashop.request.LocalTransRequestParam;
import com.seashop.service.IAppHomeConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seashop.redis.RedisZero;
import com.seashop.util.EncryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * App主页配置 服务实现类
 * </p>
 *
 * @author moredln
 * @since 2020-08-10
 */
@Service
public class AppHomeConfigServiceImpl extends ServiceImpl<AppHomeConfigMapper, AppHomeConfig> implements IAppHomeConfigService {

    @Autowired
    private AppHomeConfigMapper appHomeConfigMapper;
    @Autowired
    private ManageFeignClient manageFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private ThirdFeignClient thirdFeignClient;
    @Autowired
    private RedisZero redisZero;

    /**
     * seashop自己的翻译工具 (先查本地数据库字典,没有才找翻译工具)
     *
     * @param text
     * @param fromLanguageType
     * @param toLanguageType
     * @return
     */
    public String opTrans(String text, String fromLanguageType, String toLanguageType) {
        if (StringUtils.isBlank(text)) {
            return text;
        }
        if (fromLanguageType.equals(toLanguageType)) {
            return text;
        }
        // 先去数据字典里面查找
        String result = manageFeignClient.localTrans(new LocalTransRequestParam(text, fromLanguageType, toLanguageType));
        if (StringUtils.isBlank(result)) {
            String key = EncryptUtil.getInstance().MD5(text);
            // 先走redis缓存
            String keyRedis = BaseConstant.TRANSLATE_PREFIX + key + fromLanguageType + toLanguageType;
            if (redisZero.exists(keyRedis)) {
                return redisZero.get(keyRedis).toString();
            }
            // 走接口翻译
            result = thirdFeignClient.batchTrans(new GoogleTransRequestParam(Arrays.asList(text), fromLanguageType, toLanguageType));
            if (StringUtils.isNotBlank(result)) {
                redisZero.get(keyRedis);
            }
        }
        return result;
    }


}
